<template>
  <div class="drawer-box">
    <el-drawer v-model="visible" :direction="direction" :size="size">
      <template #header>
        <div class="header-title"><span class="icon iconfont" style="color: blue; padding-right: 10px">&#xe948;</span> 智慧小助手</div>
      </template>
      <div class="drawer-body">
        <div style="width: 100%; height: calc(100% - 160px); overflow-y: auto">
          <div class="container" style="width: 100%">
            <div v-if="error" class="error">
              {{ error.message }}
            </div>

            <Bubble :avatar-size="avatarSize" :avatar="avatarAI" v-if="content" :content="content" is-markdown />
          </div>
        </div>
        <div style="height: 160px; width: 100%; border-top: 1px solid #ebeef5">
          <div style="padding: 10px">
            <MentionSender v-model="senderValue" variant="updown" :auto-size="{ minRows: 2, maxRows: 5 }" clearable allow-speech placeholder="💌 在这里你可以自定义变体后的 prefix 和 action-list">
              <template #prefix>
                <div style="display: flex; align-items: center; gap: 8px; flex-wrap: wrap">
                  <el-button round plain color="#626aef" @click="startSSE">
                    <el-icon><Paperclip /></el-icon>
                  </el-button>
                </div>
              </template>
            </MentionSender>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script setup lang="ts">
import type { DrawerProps } from 'element-plus';
import { computed, ref } from 'vue';
import { useXStream } from 'vue-element-plus-x';
const avatarSize = '48px';
const avatarAI = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png';
const { startStream, cancel, data, error, isLoading } = useXStream();
defineOptions({
  name: 'ConversationDrawer',
});
defineProps({
  size: {
    type: Number,
    default: 1024,
  },
});
const senderValue = ref('你是谁？');
const direction = ref<DrawerProps['direction']>('rtl');
const visible = ref<boolean>(false);
const show = () => {
  visible.value = true;
};
const handleSubmit = (data: string) => {
  // visible.value = false;
};
defineExpose({
  show,
});

// 默认支持 SSE 协议
async function startSSE() {
  try {
    // const response = await fetch('https://node-test.element-plus-x.com/api/sse', {
    //   headers: { 'Content-Type': 'text/event-stream' },
    // });

    const question = senderValue.value;
    const response = await fetch('/admin-api/ai/agent/query/answer', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'text/event-stream',
      },
      body: JSON.stringify({ question }),
    });

    const readableStream = response.body!;
    await startStream({ readableStream });
  } catch (err) {
    console.error('Fetch error:', err);
  }
}

// 机器人的 content 计算属性
const content = computed(() => {
  if (!data.value.length) return '';
  let text = '';
  for (let index = 0; index < data.value.length; index++) {
    const chunk = data.value[index].data;
    try {
      // const parsedChunk = JSON.parse(chunk).content;
      text += chunk;
    } catch (error) {
      // 这个 结束标识 是后端给的，所以这里这样判断
      // 实际项目中，以项目需要为准
      if (chunk === ' [DONE]') {
        // 处理数据结束的情况
        // console.log('数据接收完毕')
      } else {
        console.error('解析数据时出错:', error);
      }
    }
    // console.log('New chunk:', chunk)
  }
  console.log('Text:', text);
  return text;
});
</script>
<style lang="scss" scoped>
.drawer-box {
  overflow: hidden;
  :deep(.el-drawer__header) {
    margin: 0;
    padding: 0 20px;
  }

  :deep(.el-drawer__body) {
    margin: 0;
    padding: 0;
  }

  :deep(.el-tabs__item) {
    width: 120px;
  }

  :deep(.el-tabs--left) {
    height: 100%;
    background: #eef1f6;
  }

  :deep(.el-tabs__content) {
    height: 100%;
    background-color: #fff;
  }

  :deep(.el-tabs--left .el-tabs__header.is-left) {
    margin: 0px;
  }

  .container {
    display: flex;
    flex-direction: column;
    width: 100%;
    gap: 12px;
    .el-button {
      width: fit-content;
    }
    :deep(.markdown-body) {
      background-color: transparent;
      padding: 12px;
    }
  }
}
</style>
